//@ts-nocheck

import { ref } from "vue"
import store from "@/store"
import { defineStore } from "pinia"
import { useTagsViewStore } from "./tags-view"
import { useSettingsStore } from "./settings"
import { getToken, removeToken, setToken } from "@/utils/cache/cookies"
import { resetRouter } from "@/router"
import { loginApi, getRoleInfo, getUserInfo, getUserPermission } from "@/api/login"
import { type LoginRequestData } from "@/api/login/types/login"
import routeSettings from "@/config/route"

import { transPwdMD5 } from "@/utils/decrypt"

export const useUserStore = defineStore("user", () => {
  const token = ref<string>(getToken() || "")
  const permissionList = ref<string[]>([])
  const user_name = ref<string>("")
  const phone = ref<string>("")
  const user_id = ref<string>("")
  const role_id = ref<number>(0)
  const role_name = ref<string>("")
  const tagsViewStore = useTagsViewStore()
  const settingsStore = useSettingsStore()

  /** 登录 */
  const login = async ({ username, password }: LoginRequestData) => {
    const decryptPwd: string = transPwdMD5(password)
    const data  = await loginApi({ username, password: decryptPwd })
    console.log('--登录返回--')
    console.log(data)
    setToken(data.token)
    token.value = data.token
    user_id.value = data.user_id
    user_name.value = data.username
    phone.value = data.phone
  }
  /** 获取用户信息 */
  const fetchUserInfo = async () => {
    const data = await getUserInfo()
    user_id.value = data.user_id
    user_name.value = data.username
    phone.value = data.phone
  }
  /** 获取角色信息 */
  const fetchRoleInfo = async () => {
    const data  = await getRoleInfo()
    role_id.value = data.id
    role_name.value = data.name
    if (role_id.value === 0) {
      role_id.value = -1 // 没有角色赋值一个-1， 防止无限循环
    }
  }

  /** 获取权限信息 */
  const fetchUserPermissions = async () => {
    const data = await getUserPermission()
    // 验证返回的 permissionList 是否为一个非空数组，否则塞入一个没有任何作用的默认角色，
    // 防止路由守卫逻辑进入无限循环
    permissionList.value = data.list.length > 0 ? data.list.map((e: { code: string }) => e.code) : ["view_home"] //[{id:0,name:"默认",code:"view_home",type:"read"}]
  }
  /** 模拟角色变化 */
  const changeRoles = async (role: string) => {
    const newToken = "token-" + role
    token.value = newToken
    setToken(newToken)
    // 用刷新页面代替重新登录
    window.location.reload()
  }
  /** 登出 */
  const logout = () => {
    removeToken()
    token.value = ""
    role_id.value = 0
    resetRouter()
    _resetTagsView()
  }
  /** 重置 Token */
  const resetToken = () => {
    removeToken()
    token.value = ""
    role_id.value = 0
    permissionList.value = []
  }
  /** 重置 Visited Views 和 Cached Views */
  const _resetTagsView = () => {
    if (!settingsStore.cacheTagsView) {
      tagsViewStore.delAllVisitedViews()
      tagsViewStore.delAllCachedViews()
    }
  }

  return { token, role_id, role_name, user_id, user_name, permissionList, login, fetchUserInfo, fetchRoleInfo, fetchUserPermissions, changeRoles, logout, resetToken }
})

/** 在 setup 外使用 */
export function useUserStoreHook() {
  return useUserStore(store)
}
